package com.bootdo.app.common.utils;


import com.bootdo.app.common.constants.JWTConstants;

import java.util.HashMap;
import java.util.Map;

/**
  * @auther: Along
  * @description: 这个类提供线程局部变量。
  * @Date: created in 2020/4/5 0:12
  */
public class ContextHandlerUtil {
    private static ThreadLocal<Map<String,Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static void setValue(String key,Object value){
        Map<String, Object> map = threadLocal.get();
        if(map == null){
            map = new HashMap<>();
            threadLocal.set(map);
        }
        map.put(key,value);
    }

    public static Object get(String key){
        Map<String, Object> map = threadLocal.get();
        if(map == null){
            map = new HashMap<>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static void remove(){
        threadLocal.remove();
    }

    public static void setCurrentUserId(Object userId){
        setValue(JWTConstants.CONTEXT_KEY_USER_ID, userId);
    }

    public static String getCurrentUserId(){
        Object o = get(JWTConstants.CONTEXT_KEY_USER_ID);
        return o == null ? null : o.toString();
    }

    public static void setCurrentUserToken(Object userToken){
        setValue(JWTConstants.CONTEXT_KEY_USER_TOKEN,userToken);
    }

    public static String getCurrentUserToken(){
        Object o = get(JWTConstants.CONTEXT_KEY_USER_TOKEN);
        return o == null ? null : o.toString();
    }

    public static void setOpenId(Object openId){
        setValue(JWTConstants.CONTEXT_KEY_USER_OPEN_ID,openId);
    }

    public static String getOpenId(){
        Object o = get(JWTConstants.CONTEXT_KEY_USER_OPEN_ID);
        return o == null ? null : o.toString();
    }


    public static void setSessionKey(Object sessionKey){
        setValue(JWTConstants.CONTEXT_KEY_USER_SESSION_KEY,sessionKey);
    }

    public static String getSessionKey(){
        Object o = get(JWTConstants.CONTEXT_KEY_USER_SESSION_KEY);
        return o == null ? null : o.toString();
    }

    public static void setSID(Object sid){
        setValue(JWTConstants.CONTEXT_KEY_USER_SID,sid);
    }

    public static String getSID(){
        Object o = get(JWTConstants.CONTEXT_KEY_USER_SID);
        return o == null ? null : o.toString();
    }


}
